import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { teamApi, teamMemberApi, teamInviteApi } from '@/api/team'
import type {
  Team,
  TeamMember,
  TeamInviteCode,
  CreateTeamRequest,
  UpdateTeamRequest,
  AddMemberRequest,
  UpdateMemberRoleRequest,
  GenerateInviteCodeRequest
} from '@/types/team'

export const useTeamStore = defineStore('team', () => {
  // 状态
  const teams = ref<Team[]>([])
  const currentTeam = ref<Team | null>(null)
  const teamMembers = ref<TeamMember[]>([])
  const teamInviteCodes = ref<TeamInviteCode[]>([])
  const loading = ref(false)
  const memberLoading = ref(false)
  const inviteCodeLoading = ref(false)

  // 在线状态相关
  const onlineStatusLoading = ref(false)
  const teamOnlineStats = ref<{
    totalMembers: number
    onlineMembers: number
    updateTime: string
  } | null>(null)

  // 计算属性
  const approvedTeams = computed(() => 
    teams.value.filter(team => team.status === 'APPROVED')
  )

  const pendingTeams = computed(() => 
    teams.value.filter(team => team.status === 'PENDING')
  )

  const currentUserRole = computed(() => {
    if (!currentTeam.value) return null
    // 这里需要根据当前用户ID获取角色，暂时返回null
    // 实际应该从用户store获取当前用户ID，然后在teamMembers中查找
    return null
  })

  const activeInviteCodes = computed(() =>
    teamInviteCodes.value.filter(code => code.status === 'ACTIVE' && code.isValid)
  )

  // Actions
  const fetchMyTeams = async () => {
    try {
      loading.value = true
      console.log('=== 获取团队列表 ===')
      const response = await teamApi.getMyTeams()
      console.log('API响应:', response)
      console.log('团队数据:', response.data)
      console.log('团队数量:', response.data?.length || 0)
      teams.value = response.data
      console.log('Store中的teams:', teams.value)
      console.log('========================')
    } catch (error) {
      console.error('获取团队列表失败:', error)
      ElMessage.error('获取团队列表失败')
    } finally {
      loading.value = false
    }
  }

  const fetchTeamDetail = async (teamId: number) => {
    try {
      loading.value = true
      const response = await teamApi.getTeamDetail(teamId)
      currentTeam.value = response.data
      return response.data
    } catch (error) {
      console.error('获取团队详情失败:', error)
      ElMessage.error('获取团队详情失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  const createTeam = async (data: CreateTeamRequest) => {
    try {
      loading.value = true
      const response = await teamApi.createTeam(data)
      teams.value.unshift(response.data)
      ElMessage.success('团队创建成功，等待管理员审核')
      return response.data
    } catch (error: any) {
      console.error('创建团队失败:', error)

      // 提取具体的错误信息
      let errorMessage = '创建团队失败'
      if (error?.response?.data?.message) {
        // 后端返回的具体错误信息
        errorMessage = error.response.data.message
      } else if (error?.message) {
        // 网络错误等
        errorMessage = error.message
      }

      ElMessage.error(errorMessage)
      throw error
    } finally {
      loading.value = false
    }
  }

  const updateTeam = async (teamId: number, data: UpdateTeamRequest) => {
    try {
      loading.value = true
      const response = await teamApi.updateTeam(teamId, data)
      
      // 更新本地数据
      const index = teams.value.findIndex(team => team.id === teamId)
      if (index !== -1) {
        teams.value[index] = response.data
      }
      if (currentTeam.value?.id === teamId) {
        currentTeam.value = response.data
      }
      
      ElMessage.success('团队信息更新成功')
      return response.data
    } catch (error) {
      console.error('更新团队失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const deleteTeam = async (teamId: number) => {
    try {
      await ElMessageBox.confirm(
        '确定要删除这个团队吗？此操作不可恢复。',
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      loading.value = true
      await teamApi.deleteTeam(teamId)
      
      // 更新本地数据
      teams.value = teams.value.filter(team => team.id !== teamId)
      if (currentTeam.value?.id === teamId) {
        currentTeam.value = null
      }
      
      ElMessage.success('团队删除成功')
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除团队失败:', error)
        throw error
      }
    } finally {
      loading.value = false
    }
  }

  // 团队成员管理
  const fetchTeamMembers = async (teamId: number) => {
    try {
      memberLoading.value = true
      const response = await teamMemberApi.getTeamMembers(teamId)
      teamMembers.value = response.data
    } catch (error) {
      console.error('获取团队成员失败:', error)
      ElMessage.error('获取团队成员失败')
    } finally {
      memberLoading.value = false
    }
  }

  const addTeamMember = async (teamId: number, data: AddMemberRequest) => {
    try {
      memberLoading.value = true
      const response = await teamMemberApi.addTeamMember(teamId, data)
      teamMembers.value.push(response.data)

      // 更新团队成员数量
      if (currentTeam.value?.id === teamId) {
        currentTeam.value.currentMembers++
      }
      const teamIndex = teams.value.findIndex(team => team.id === teamId)
      if (teamIndex !== -1) {
        teams.value[teamIndex].currentMembers++
      }

      ElMessage.success('成员添加成功')
      return response.data
    } catch (error: any) {
      console.error('添加成员失败:', error)

      // 提取具体的错误信息
      let errorMessage = '添加成员失败'
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message
      } else if (error?.message) {
        errorMessage = error.message
      }

      ElMessage.error(errorMessage)
      throw error
    } finally {
      memberLoading.value = false
    }
  }

  const removeTeamMember = async (teamId: number, userId: number) => {
    try {
      await ElMessageBox.confirm(
        '确定要移除这个成员吗？',
        '确认移除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      memberLoading.value = true
      await teamMemberApi.removeTeamMember(teamId, userId)
      
      // 更新本地数据
      teamMembers.value = teamMembers.value.filter(member => member.userId !== userId)
      
      // 更新团队成员数量
      if (currentTeam.value?.id === teamId) {
        currentTeam.value.currentMembers--
      }
      const teamIndex = teams.value.findIndex(team => team.id === teamId)
      if (teamIndex !== -1) {
        teams.value[teamIndex].currentMembers--
      }
      
      ElMessage.success('成员移除成功')
    } catch (error) {
      if (error !== 'cancel') {
        console.error('移除成员失败:', error)
        throw error
      }
    } finally {
      memberLoading.value = false
    }
  }

  const updateMemberRole = async (teamId: number, userId: number, data: UpdateMemberRoleRequest) => {
    try {
      memberLoading.value = true
      const response = await teamMemberApi.updateMemberRole(teamId, userId, data)
      
      // 更新本地数据
      const index = teamMembers.value.findIndex(member => member.userId === userId)
      if (index !== -1) {
        teamMembers.value[index] = response.data
      }
      
      ElMessage.success('成员角色更新成功')
      return response.data
    } catch (error) {
      console.error('更新成员角色失败:', error)
      throw error
    } finally {
      memberLoading.value = false
    }
  }

  // 邀请码管理
  const fetchTeamInviteCodes = async (teamId: number) => {
    try {
      inviteCodeLoading.value = true
      const response = await teamInviteApi.getTeamInviteCodes(teamId)
      teamInviteCodes.value = response.data
    } catch (error) {
      console.error('获取邀请码列表失败:', error)
      ElMessage.error('获取邀请码列表失败')
    } finally {
      inviteCodeLoading.value = false
    }
  }

  const generateInviteCode = async (teamId: number, data: GenerateInviteCodeRequest) => {
    try {
      inviteCodeLoading.value = true
      const response = await teamInviteApi.generateInviteCode(teamId, data)
      teamInviteCodes.value.unshift(response.data)
      ElMessage.success('邀请码生成成功')
      return response.data
    } catch (error) {
      console.error('生成邀请码失败:', error)
      throw error
    } finally {
      inviteCodeLoading.value = false
    }
  }

  const joinTeamByInviteCode = async (inviteCode: string) => {
    try {
      loading.value = true
      const response = await teamInviteApi.joinTeamByInviteCode(inviteCode)
      ElMessage.success('成功加入团队')

      // 重新获取团队列表
      await fetchMyTeams()

      return response.data
    } catch (error: any) {
      console.error('加入团队失败:', error)

      // 提取具体的错误信息
      let errorMessage = '加入团队失败'
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message
      } else if (error?.message) {
        errorMessage = error.message
      }

      ElMessage.error(errorMessage)
      throw error
    } finally {
      loading.value = false
    }
  }

  const disableInviteCode = async (teamId: number, codeId: number) => {
    try {
      inviteCodeLoading.value = true
      await teamInviteApi.disableInviteCode(teamId, codeId)
      
      // 更新本地数据
      const index = teamInviteCodes.value.findIndex(code => code.id === codeId)
      if (index !== -1) {
        teamInviteCodes.value[index].status = 'DISABLED'
        teamInviteCodes.value[index].isValid = false
      }
      
      ElMessage.success('邀请码已禁用')
    } catch (error) {
      console.error('禁用邀请码失败:', error)
      throw error
    } finally {
      inviteCodeLoading.value = false
    }
  }

  const refreshInviteCode = async (teamId: number, codeId: number) => {
    try {
      inviteCodeLoading.value = true
      const response = await teamInviteApi.refreshInviteCode(teamId, codeId)
      
      // 更新本地数据
      const index = teamInviteCodes.value.findIndex(code => code.id === codeId)
      if (index !== -1) {
        teamInviteCodes.value[index] = response.data
      }
      
      ElMessage.success('邀请码已刷新')
      return response.data
    } catch (error) {
      console.error('刷新邀请码失败:', error)
      throw error
    } finally {
      inviteCodeLoading.value = false
    }
  }

  // 管理员审核团队
  const approveTeam = async (teamId: number, approved: boolean) => {
    try {
      loading.value = true
      const response = await teamApi.approveTeam(teamId, approved)

      // 更新本地团队状态
      const teamIndex = teams.value.findIndex(team => team.id === teamId)
      if (teamIndex !== -1) {
        teams.value[teamIndex].status = approved ? 'APPROVED' : 'REJECTED'
      }

      if (currentTeam.value?.id === teamId) {
        currentTeam.value.status = approved ? 'APPROVED' : 'REJECTED'
      }

      const message = approved ? '团队审核通过' : '团队已拒绝'
      ElMessage.success(message)
      return response.data
    } catch (error: any) {
      console.error('审核团队失败:', error)

      let errorMessage = '审核团队失败'
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message
      } else if (error?.message) {
        errorMessage = error.message
      }

      ElMessage.error(errorMessage)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 转移团队所有权
  const transferOwnership = async (teamId: number, newOwnerId: number) => {
    try {
      loading.value = true
      const response = await teamApi.transferOwnership(teamId, newOwnerId)

      // 刷新团队成员列表
      await fetchTeamMembers(teamId)

      ElMessage.success('所有权转移成功')
      return response.data
    } catch (error: any) {
      console.error('转移所有权失败:', error)

      let errorMessage = '转移所有权失败'
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message
      } else if (error?.message) {
        errorMessage = error.message
      }

      ElMessage.error(errorMessage)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取团队成员在线状态
  const fetchTeamMembersOnlineStatus = async (teamId: number) => {
    try {
      onlineStatusLoading.value = true
      const response = await teamApi.getTeamMembersOnlineStatus(teamId)

      if (response.success) {
        // 更新团队成员的在线状态
        const onlineStatusData = response.data
        console.log('🔍 在线状态数据:', onlineStatusData)

        // 更新teamMembers中每个成员的在线状态
        teamMembers.value = teamMembers.value.map(member => {
          const memberWithStatus = onlineStatusData.members.find(
            m => m.userId === member.userId
          )

          if (memberWithStatus) {
            console.log(`🔍 更新成员 ${member.userId} 在线状态:`, memberWithStatus.isOnline)
            return {
              ...member,
              isOnline: memberWithStatus.isOnline,
              lastActiveTime: memberWithStatus.lastActiveTime,
              onlineStatus: memberWithStatus.status
            }
          }

          return {
            ...member,
            isOnline: false,
            onlineStatus: 'OFFLINE'
          }
        })

        // 存储在线状态统计
        teamOnlineStats.value = {
          totalMembers: onlineStatusData.totalMembers,
          onlineMembers: onlineStatusData.onlineMembers,
          updateTime: onlineStatusData.updateTime
        }

        return response.data
      }
    } catch (error: any) {
      console.error('获取团队成员在线状态失败:', error)
      throw error
    } finally {
      onlineStatusLoading.value = false
    }
  }

  // 重置状态
  const resetState = () => {
    teams.value = []
    currentTeam.value = null
    teamMembers.value = []
    teamInviteCodes.value = []
    loading.value = false
    memberLoading.value = false
    inviteCodeLoading.value = false
  }

  return {
    // 状态
    teams,
    currentTeam,
    teamMembers,
    teamInviteCodes,
    loading,
    memberLoading,
    inviteCodeLoading,
    onlineStatusLoading,
    teamOnlineStats,
    
    // 计算属性
    approvedTeams,
    pendingTeams,
    currentUserRole,
    activeInviteCodes,
    
    // Actions
    fetchMyTeams,
    fetchTeamDetail,
    createTeam,
    updateTeam,
    deleteTeam,
    fetchTeamMembers,
    addTeamMember,
    removeTeamMember,
    updateMemberRole,
    fetchTeamInviteCodes,
    generateInviteCode,
    joinTeamByInviteCode,
    disableInviteCode,
    refreshInviteCode,
    approveTeam,
    transferOwnership,
    fetchTeamMembersOnlineStatus,
    resetState
  }
})
